/**
 *   This file is part of GeoArticle (a Joomla plugin).
 *   Written by Ivar Bergman (www.ivarbergman.se)
 *   Copyright (c) 2010 Ivar Bergman. All rights reserved.
 *
 *   GeoArticle is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   GeoArticle is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with GeoArticle.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

function GAMapUI()
{
  var me = this;
  var mgrOptions = { borderPadding: 100, maxZoom: GAConf.maxZoom, trackMarkers: false };
  GAMarkup($(GAConf.divHookID));
  $(GAConf.divHookID).width(GAConf.width);
  $(GAConf.divHookID).height(GAConf.height);
  jQuery(window).unload(GUnload);

  this.map = new GMap2(document.getElementById("map_canvas"));
  this.map.setCenter(GAConf.home, GAConf.zoom);
  this.mgr = new MarkerManager(this.map, mgrOptions);
  this.content = $("#map_info_content");
  this.window = $("#map_info");

  GAConf.standard = false;
  if ( GAConf.print)
    {
      $("#map_type").hide();
      $("#map_ctrl").hide();
    }
  if ( GAConf.skin == 'google' )
    {
      GAConf.standard = true;
      var topLeft = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(90,10));
      var mtype = new GMapTypeControl();
      this.map.addControl(mtype, topLeft);
      this.map.addControl(new GLargeMapControl3D());
      $("#map_ctrl").hide();
      $("#map_type").hide();
    }

  $("#print_map").click(function(){
    if ($.getUrlVar("print"))
      {
	window.print();
      }
    else
      {

	var url = window.location.href.replace("index.php", "index2.php");
	var cats = $.map($("#map_menu_list").find("a.active"), function(elm, idx) {return $(elm).aOp(); } );
	url += "&print=1&geocat=" + cats.join(",") ;
	window.open(url,"visitfinnskogen_print_map","status=no,toolbar=no,scrollbars=yes,titlebar=no,menubar=no,resizable=yes,width=900,height=700,directories=no,location=no");
	return false;
      }
  });

  $("#map_type a").click(function(event) {
    var type = $(event.currentTarget).aOp();
    GA.trigger("mapType", type);
    return false;
  });

  $("#map_ctrl a").click(function(event){
    var eventType = $(event.currentTarget).aOp();
    GA.trigger(eventType);
    return false;
  });

  $("#map_info .close").click(function(event) {
    GA.trigger("closeArticle", GA.data("activeMarker"));
    return false;
  });


  $("#track").slider({
    range: "max",
    orientation: "vertical",
    min: GAConf.minZoom,
    max: GAConf.maxZoom,
    value: GAConf.zoom,
    change: function(event, ui)
      {
	GA.trigger("zoom", ui.value);
      }
    });

    // Add a click event, to open a info window with the article.
    GEvent.addListener(me.map, "zoomend", function(event)
      {
	$("#track").slider("value", me.map.getZoom());
	GA.trigger("hideActiveLabel");
      });


  GA.bind("center", function(event) {
    me.map.setCenter(GAConf.home, GAConf.zoom);
    $("#track").slider("value", GAConf.zoom);
  });

  GA.bind("zoom", function(event, value) {
    me.map.setZoom(value);
  });

  GA.bind("in", function(event) {
    me.map.zoomIn();
    var v = $("#track").slider("value") + 1;
    v = (v>20) ? 20 : v;
    $("#track").slider("value", v);
  });

  GA.bind("out", function(event) {
    me.map.zoomOut();
    var v = $("#track").slider("value") - 1;
    v = (v<0) ? 0 : v;
    $("#track").slider("value", v);
  });

  GA.bind("up", function(event) {
    me.map.panDirection(0, 1);
  });

  GA.bind("down", function(event) {
    me.map.panDirection(0, -1);
  });

  GA.bind("left", function(event) {
    me.map.panDirection(1, 0);
  });

  GA.bind("right", function(event) {
    me.map.panDirection(-1, 0);
  });

  GA.bind("mapType", function(event, type) {
    $("#map_type a").removeClass("active");
    $("#map_type a."+type).addClass("active");
    switch (type)
      {
      case "normal":
	me.map.setMapType(G_NORMAL_MAP);
	break;
      case "satellite":
	me.map.setMapType(G_SATELLITE_MAP );
	break;
      case "physical":
	me.map.setMapType(G_PHYSICAL_MAP);
	break;
      }
  });
  GA.bind("showCategory", function(event, id) {
    me.mgr.refresh();
    GA.trigger("hideActiveLabel");
  });

  GA.bind("hideCategory", function(event, id) {
    me.mgr.refresh();
    GA.trigger("hideActiveLabel");
  });

  GA.bind("openArticle", function(event, marker) {
    var url = GAConf.urlArticle.replace("#cid#", marker.id);
    var print = GAConf.urlPrint.replace("#cid#", marker.id);
    var active = GA.data("activeMarker");
    if (active)
      {
	GA.trigger("closeArticle", active);
      }

    marker.open = true;
    GA.data("activeMarker", marker);
	    GA.trigger("showLabel", marker);

    me.content.attr("src", url);
    me.window.show();

    $("#print").attr("href", print);
    $("#print").click(function(){
      window.open(this.href,"visitfinnskogen_print","status=no,toolbar=no,scrollbars=yes,titlebar=no,menubar=no,resizable=yes,width=640,height=480,directories=no,location=no");
      return false;
    });

});

  GA.bind("showLabel", function(event, marker) {
	var n = marker.geoTagDomNode();
	var astr = "mouseover_"+marker.id;
	var a = $("#"+astr);
	if (a.length == 0)
	  {

	    var p = n.parent();
	    a = $('<span>'+marker.labelTitle+'</span>')
	      .addClass("map_marker_active")
	      .addClass("map_marker_normal")
	      .attr("id", astr);

	    p.append(a);
	    n.css('z-index', 1e9);

	  }

	  a.css("top", parseInt(n.css("top")) + 2)
	      .css("left", parseInt(n.css("left")) + 26)
	      .css('z-index', 1e9);
	  var img = marker.getIcon().image;
	  if (img.indexOf("_hover.png") == -1)
	    {
	      var nimg = img.replace(".png","_hover.png");
	      marker.setImage(nimg);
	    }


  });
  GA.bind("hideActiveLabel", function(event) {
    var active = GA.data("activeMarker");
    if (active)
      {
	GA.trigger("hideLabel", [active, true]);
      }
  });

  GA.bind("hideLabel", function(event, marker, force) {

	if (marker.open != true || force == true)
	  {
	    var n = marker.geoTagDomNode();
	    var z = GOverlay.getZIndex(marker.getLatLng().lat());
	    n.css('z-index', z);
	    var a = $("#mouseover_"+marker.id);
	    if (a.length > 0)
	      {
		a.remove();
	      }
	    var img = marker.getIcon().image;
	    var nimg = img.replace("_hover", "");
	    marker.setImage(nimg);

	    }
  });

  GA.bind("closeArticle", function(event, marker) {
    marker.open = false;
    GA.trigger("hideLabel", marker);
    me.window.hide();
  });

  GA.bind("addMarker", function(event, marker) {


    // Add a mouseover event, to show the marker title in a small hover element.
    GEvent.addListener(marker, "mouseover", function()
      {
	GA.trigger("showLabel", this);
      });

    // Add a mouseout event, to remove the marker title.
    GEvent.addListener(marker, "mouseout", function()
      {
	GA.trigger("hideLabel", this);
      });

    // Add a click event, to open a info window with the article.
    GEvent.addListener(marker, "click", function()
      {
	me.map.panTo(this.getLatLng());
	GA.trigger("openArticle", marker);
      });


    // Add the marker to the markermanager
    me.mgr.addMarker(marker, 0, 17);

    // Find the jQuery img-element for the marker, and add a class.
    var m = marker.geoTagDomNode();
    m.addClass("map_marker");

    // Refresh the markermanager to show the markers.
    me.mgr.refresh();
  });

};


function GANavigationUI()
{
  var me = this;
  this.node = $("#map_menu");
  this.list = $("#map_menu_list");

  // Draw ui markup on add event
  GA.bind("addCategory", function(event, cat) {
    var a = $("<a href='#"+cat.id+"' class='checkbox'>"+cat.title+"</a>")
      .click(function(event) {
	var op = $(event.currentTarget).aOp();
	if ($(this).hasClass("active"))
	  {
	    cat.hide();
	  }
	else
	  {
	    cat.show();
	  }
	return false;
      });
    var li = $("<li></li>");
    li.append(a);
    me.list.append(li);
  });

  // Gui listener to react on show event
  GA.bind("showCategory", function(event, cat) {
    var s = "a[href$='#"+cat.id+"']";
    var target = me.node.find(s);
	    console.log("show category " + cat.id);
	    console.log("show category " + target.length);
	    	    console.log("show category " + s);
    target.addClass("active");
  });

  // Gui listener to react on hide event
  GA.bind("hideCategory", function(event, cat) {
    var s = "a[href$='#"+cat.id+"']";
    var target = me.node.find(s);
    target.removeClass("active");
  });
}

GANavigationUI.prototype.showDefaultCategories = function()
{
  var str = $.getUrlVar("geocat");
  if (!str)
    {
      return;
    }
  var cats = str.split(",");
  for(var i = 0; i < cats.length; i++)
    {
      cat = cats[i];
      GAApp.showCategory(cat);
    }

};


function GAMarkup(node)
{
  return ;
  node.append( $("\
      <div id='map_canvas'></div> \
      <div id='map_ctrl'> \
	<div class='map_pos'>\
          <a class='up' href='#up'></a>\
	  <a class='left' href='#left'></a>\
	  <a class='center' href='#center'></a>\
	  <a class='right' href='#right'></a>\
	  <a class='down' href='#down'></a>\
	</div>\
	<div class='map_zoom'>\
	  <a class='in' href='#in'></a>\
	  <a class='out' href='#out'></a>\
	  <div id='track'></div>\
	</div>\
      </div>\
      <div id='map_type'>\
	<a class='normal' href='#normal'><span>Map</span></a>\
	<a class='satellite' href='#satellite'><span>Sat</span></a>\
	<a class='physical' href='#physical'><span>Ter</span></a>\
      </div>\
      <div id='map_menu'>\
       <div id='map_menu_bg'>\
	<ul id='map_menu_list'>\
	  <li class='header'>\
	    <h2><span style='float:left;'>Aktiviteter</span><a id='print_map' class='print' rel='nofollow' title='Print' href='#' style='float:right;'><img style='float: right;' src='"+GAConf.skinBase+"/printButton.png'  alt='Print'/></a></h2>\
	  </li>\
	</ul>\
	</div>\
	<div id='map_menu_bottom'>\
	</div>\
      </div>\
      <div id='map_info'>\
	<div id='map_info_header'>\
	  <div id='map_info_header_right'>\
	  <a class='close' href='#close'></a><!-- \");  -->\
<a id='print' class='print' rel='nofollow' title='Print' href=''><img style='float: right;' src='"+GAConf.skinBase+"printButton.png'  alt='Print'/></a>\
          </div>\
	</div>\
	<div id='map_info_body'>\
  	  <iframe allowtransparency='true' frameborder='0' id='map_info_content'></iframe>\
	</div>\
      </div>\
") );


}

GMarker.prototype.geoTagDomNode = function()
{
  var qm = "img[id$='"+this.id+"']";
  var m = $(qm).first();
  return m;
};

GMarker.prototype.geoTagMouseOver = function()
{
  var img = this.getIcon().image;
  var nimg = img.replace(".png","_hover.png");
  this.setImage(nimg);

};

GMarker.prototype.geoTagMouseOut = function()
{
  if (this.open != true)
    {
      var img = this.getIcon().image;
      var nimg = img.replace("_hover", "");
      this.setImage(nimg);
    }
};

$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});